<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    header {
      width: 375px;
      height: 60px;
      font-size: 20px;
      background-color: lightcoral;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  </style>
</head>
<body>
  <div id="app">
    <h2>依赖注入</h2>
    <!-- 依赖注入默认是没有响应式的 -->
    <button @click="count++">count++</button><span>{{ count }}</span>
    <grand-father></grand-father>
  </div>

  <script src="../vue3.js"></script>
  <script>
    const {createApp, computed} = Vue;


    const ageSymbol = Symbol();
    const ageSymbol2 = Symbol();


    const Son = {
      // inject: ["count", "age"], 
      inject: {
        count: {
          from: "count"
        },
        age: {
          from: ageSymbol
        },
        age2: {
          from: ageSymbol2
        }
      },
      template: `
        <div>这是孙子组件 - {{ count }} - {{ age }} - {{ age2 }}</div>
      `
    }

    const Father = {
      // inject: ["name"],

      // inject还可以写成对象的语法，可以给注入的变量改一个名字
      // 让它不与组件已有的变量名相冲突

      // default表示的是注入的默认值
      inject: {
        otherName: {
          from: "name",
          default: "wangwu",
        },
      },
      data() {
        return {
          name: "lisi"
        }
      },
      components: {
        Son,
      },
      template: `
        <div>这是爸爸组件 - {{ otherName }}</div>
        <son></son>
      `
    }

    const GrandFather = {
      components: {
        Father,
      },
      template: `
        <div>这是爷爷组件</div>
        <father></father>
      `,
      provide() {
        return {
          [ageSymbol2]: 100
        }
      }
    }

    const app = createApp({
      data() {
        return {
          count: 100
        }
      },
      components: {
        GrandFather
      },
      // provide表示的是依赖
      provide() {
        return {
          // count: this.count,

          // 如果需要用到响应式，可以从Vue里面解构computed方法
          count: computed(() => this.count),
          name: "zhangsan",
          [ageSymbol]: 200,
        }
      }
    });

    app.mount("#app");
  </script>
</body>
</html>